<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useCampfireStore } from '../stores/campfireStore'
import { useMindArchiveStore } from '../stores/mindArchiveStore'
import { Search, Plus, MagicStick, Filter, Clock, Check, QuestionFilled } from '@element-plus/icons-vue'

const router = useRouter()
const campfireStore = useCampfireStore()
const mindArchiveStore = useMindArchiveStore()

// 筛选状态
const activeTab = ref('latest') // latest, hot, unsolved, solved
const searchKeyword = ref('')
const selectedTags = ref([])

// 获取所有标签（从帖子中提取）
const allTags = computed(() => {
  const tagSet = new Set()
  campfireStore.allPosts.forEach(post => {
    post.tags.forEach(tag => tagSet.add(tag))
  })
  return Array.from(tagSet)
})

// 根据筛选条件获取帖子
const filteredPosts = computed(() => {
  // 首先按关键词和标签筛选
  let result = campfireStore.allPosts
  
  if (searchKeyword.value) {
    result = campfireStore.searchPostsByKeyword(searchKeyword.value)
  }
  
  if (selectedTags.value.length > 0) {
    result = campfireStore.searchPostsByTags(selectedTags.value)
  }
  
  // 然后按选项卡筛选
  switch (activeTab.value) {
    case 'latest':
      return [...result].sort((a, b) => new Date(b.createTime) - new Date(a.createTime))
    case 'hot':
      return [...result].sort((a, b) => b.viewCount - a.viewCount)
    case 'unsolved':
      return result.filter(post => post.status === 'unsolved')
    case 'solved':
      return result.filter(post => post.status === 'solved')
    default:
      return result
  }
})

// 创建新帖子
function createNewPost() {
  router.push('/campfire/create')
}

// 查看帖子详情
function viewPostDetail(postId) {
  // 增加查看次数
  campfireStore.increasePostViewCount(postId)
  router.push(`/campfire/post/${postId}`)
}

// 格式化时间显示
function formatTime(timeString) {
  const date = new Date(timeString)
  const now = new Date()
  const diffMs = now - date
  const diffSec = Math.floor(diffMs / 1000)
  const diffMin = Math.floor(diffSec / 60)
  const diffHour = Math.floor(diffMin / 60)
  const diffDay = Math.floor(diffHour / 24)
  
  if (diffDay > 0) {
    return `${diffDay}天前`
  } else if (diffHour > 0) {
    return `${diffHour}小时前`
  } else if (diffMin > 0) {
    return `${diffMin}分钟前`
  } else {
    return '刚刚'
  }
}

// 格式化投入时间显示
function formatInvestedTime(minutes) {
  if (minutes < 60) {
    return `${minutes}分钟`
  } else {
    const hours = Math.floor(minutes / 60)
    const mins = minutes % 60
    return mins > 0 ? `${hours}小时${mins}分钟` : `${hours}小时`
  }
}
</script>

<template>
  <div class="campfire-container">
    <div class="campfire-header">
      <div class="header-content">
        <h1 class="header-title">
          <el-icon class="fire-icon"><MagicStick /></el-icon>
          探索营地
        </h1>
        <p class="header-subtitle">独自思考，不如一起探索。Think alone, explore together.</p>
      </div>
      <el-button type="primary" @click="createNewPost" class="create-post-btn">
        <el-icon><Plus /></el-icon>
        分享我的卡点
      </el-button>
    </div>
    
    <div class="filter-section">
      <div class="search-box">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索帖子标题、描述或卡点"
          :prefix-icon="Search"
          clearable
        />
      </div>
      
      <div class="tag-filter">
        <el-select
          v-model="selectedTags"
          multiple
          collapse-tags
          collapse-tags-tooltip
          placeholder="按标签筛选"
          :prefix-icon="Filter"
        >
          <el-option
            v-for="tag in allTags"
            :key="tag"
            :label="tag"
            :value="tag"
          />
        </el-select>
      </div>
    </div>
    
    <div class="tabs-section">
      <el-tabs v-model="activeTab" class="filter-tabs">
        <el-tab-pane label="最新" name="latest">
          <el-icon><Clock /></el-icon>
        </el-tab-pane>
        <el-tab-pane label="最热" name="hot">
-          <el-icon><Fire /></el-icon>
+          <el-icon><MagicStick /></el-icon>
         </el-tab-pane>
        <el-tab-pane label="未解决" name="unsolved">
          <el-icon><QuestionFilled /></el-icon>
        </el-tab-pane>
        <el-tab-pane label="已破解" name="solved">
          <el-icon><Check /></el-icon>
        </el-tab-pane>
      </el-tabs>
    </div>
    
    <div class="posts-list">
      <template v-if="filteredPosts.length > 0">
        <div 
          v-for="post in filteredPosts" 
          :key="post.id"
          class="post-card"
          @click="viewPostDetail(post.id)"
        >
          <div class="post-header">
            <h3 class="post-title">{{ post.title }}</h3>
            <div class="post-meta">
              <span class="post-time">{{ formatTime(post.createTime) }}</span>
              <span class="post-views">{{ post.viewCount }} 次查看</span>
            </div>
          </div>
          
          <div class="post-invested-time">
            <el-icon><Clock /></el-icon>
            已探索 {{ formatInvestedTime(post.investedTime) }}
          </div>
          
          <div class="post-description">{{ post.description }}</div>
          
          <div class="post-tags">
            <el-tag 
              v-for="tag in post.tags" 
              :key="tag"
              size="small"
              effect="plain"
              class="post-tag"
            >
              {{ tag }}
            </el-tag>
          </div>
          
          <div class="post-status">
            <el-tag 
              :type="post.status === 'solved' ? 'success' : 'info'"
              effect="light"
              size="small"
            >
              {{ post.status === 'solved' ? '已破解' : '未解决' }}
            </el-tag>
          </div>
        </div>
      </template>
      
      <div v-else class="empty-state">
        <el-empty description="暂无帖子" />
        <el-button type="primary" @click="createNewPost">分享第一个卡点</el-button>
      </div>
    </div>
  </div>
</template>

<style scoped>
.campfire-container {
  max-width: 1000px;
  margin: 0 auto;
  padding: 20px;
}

.campfire-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
}

.header-content {
  flex: 1;
}

.header-title {
  font-size: 28px;
  margin: 0;
  display: flex;
  align-items: center;
}

.fire-icon {
  color: #ff7d00;
  margin-right: 10px;
  font-size: 28px;
}

.header-subtitle {
  color: #666;
  margin: 5px 0 0;
  font-size: 16px;
}

.create-post-btn {
  font-weight: bold;
}

.filter-section {
  display: flex;
  gap: 15px;
  margin-bottom: 20px;
}

.search-box {
  flex: 1;
}

.tag-filter {
  width: 250px;
}

.filter-tabs {
  margin-bottom: 20px;
}

.posts-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.post-card {
  border: 1px solid #eee;
  border-radius: 8px;
  padding: 20px;
  transition: all 0.3s ease;
  position: relative;
  cursor: pointer;
}

.post-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  border-color: #ddd;
}

.post-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 10px;
}

.post-title {
  margin: 0;
  font-size: 18px;
  flex: 1;
}

.post-meta {
  display: flex;
  gap: 15px;
  color: #999;
  font-size: 14px;
}

.post-invested-time {
  display: flex;
  align-items: center;
  gap: 5px;
  color: #ff7d00;
  font-weight: bold;
  margin-bottom: 10px;
  font-size: 14px;
}

.post-description {
  margin-bottom: 15px;
  color: #333;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}

.post-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-bottom: 10px;
}

.post-tag {
  cursor: pointer;
}

.post-status {
  position: absolute;
  top: 20px;
  right: 20px;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 20px;
  padding: 40px 0;
}
</style>